"""
登陆申诉
"""
import logging

from biz.core.thanos.models import LoginOrder
from biz.exceptions import ERROR_DATA_NOT_EXISTS, ERROR_NO_PERMISSION_OPERATION, ERROR_DATA_STATUS
from biz.const import LoginOrderStatus
from gis.common.django_ext.models import paginate
from gis.common.exceptions import BizException

_LOGGER = logging.getLogger(__name__)


def list_login_order(page_no, page_size, pro_id=None, data_id=None, net=None, contact_type=None, status=None,
                     created_at_start=None, created_at_end=None):
    assert page_no > 0
    assert page_size > 0
    query = LoginOrder.objects.all()
    if pro_id:
        query = query.filter(pro_id=pro_id)
    if data_id:
        query = query.filter(pk=data_id)
    if net is not None:
        query = query.filter(net=net)
    if contact_type:
        query = query.filter(contact_type=contact_type)
    if status is not None:
        query = query.filter(status=status)
    if created_at_start:
        query = query.filter(created_at__gte=created_at_start)
    if created_at_end:
        query = query.filter(created_at__lte=created_at_end)

    return query.count(), [e.to_dict() for e in paginate(query.order_by('created_at'), page_no, page_size)]


def add_login_order(pro_id=None, appear_at=None, images=None, desc=None, contact_type=None, contact_account=None,
                    net=None, phone_model=None):
    login_order = LoginOrder.objects.create(pro_id=pro_id, appear_at=appear_at, images=images, desc=desc, net=net,
                                            contact_type=contact_type, contact_account=contact_account,
                                            phone_model=phone_model)
    return login_order.to_dict()


def get_login_order(data_id):
    data = _get_data(data_id)
    return data.to_dict()


def update_login_order(data_id, status=None, remark=None, handler_id=None):
    data = _get_data(data_id)
    if data.status == LoginOrderStatus.WAITING:  # 未处理的
        if status not in [LoginOrderStatus.WORKING, LoginOrderStatus.FINISHED]:
            raise BizException(ERROR_DATA_STATUS)
        data.handler_id = handler_id
    elif data.status == LoginOrderStatus.WORKING:  # 处理中的
        if data.handler_id != handler_id:
            raise BizException(ERROR_NO_PERMISSION_OPERATION)
        if status != LoginOrderStatus.FINISHED:
            raise BizException(ERROR_DATA_STATUS)
    elif data.status == LoginOrderStatus.FINISHED:  # 已处理的
        raise BizException(ERROR_DATA_STATUS)
    data.status = status
    data.remark = remark
    data.save()
    return data.to_dict()


def _get_data(data_id):
    assert data_id > 0
    data = LoginOrder.objects.filter(pk=data_id).first()
    if not data:
        raise BizException(ERROR_DATA_NOT_EXISTS)
    return data
